<template>
  <div>
    <!-- 岗位管理 -->
    <custom-container ref="customContainerRef" :config="mainConfig" />
    <setForm
      ref="setFormRef"
      v-model:open="open"
      v-model:title="title"
      @changeList="handleQuery"
    />
  </div>
</template>
<script lang="ts" setup>
import { Delete, Plus, Download, Edit } from '@element-plus/icons-vue'
import { ref, getCurrentInstance, defineAsyncComponent, computed } from 'vue'
import { ElMessage, ElMessageBox, ElButton } from 'element-plus'
import { useI18n } from 'vue-i18n'
import { DictDirection } from '@/store/modules/dicts'
import { listRole, delRole } from '@/api/system/role'

const setForm = defineAsyncComponent(() => import('./components/setForm.vue'))
const { t } = useI18n()
const

  // 非单个禁用
  single = ref(true),
  // 非多个禁用
  multiple = ref(true),
  open = ref(false),
  title = ref(undefined),
  // 查询参数
  queryParams = ref({
    pageNum: 1,
    pageSize: 10,
    roleName: undefined,
    roleKey: undefined,
    status: undefined,
  }),
  customContainerRef = ref(null),
  setFormRef = ref(null),
  {
    proxy,

  }:{
    proxy:any
 
  } = getCurrentInstance()
let ids = []
// 搜索
const handleQuery = () => {
  customContainerRef.value.getList()
}
// 列表选择
const handleSelectionChange = (rows: { [key: string]: any }[]) => {
  ids = rows.map((item) => item.roleId)
  single.value = rows.length != 1
  multiple.value = !rows.length
}
// 新增岗位
const handleAdd = () => {
  open.value = true
  title.value = '新增岗位'
}
// 修改岗位
const handleUpdate = (row: { [key: string]: any }) => {
  open.value = true
  title.value = '修改岗位'
  const rowList = JSON.parse(JSON.stringify(row))
  const roleId = row?.roleId || ids
  setFormRef.value.form = rowList
  proxy.$nextTick(() => {
    setFormRef.value.getRoleMenuTreeselect(roleId).then(res => setFormRef.value.menu.setCheckedKeys(res.data.checkedKeys))
  })
}
// 删除岗位
const handleDelete = (row: { [key: string]: any }) => {
  const roleIds = row.roleId || ids
  console.log(roleIds)
  ElMessageBox.confirm(`是否确认删除用户编号为"${ roleIds }"的数据项?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
  .then(() => delRole(roleIds))
  .then((res) => {
    if (res.code === 200) {
      console.log('ss')
      handleQuery()
      ElMessage.success('删除成功')
    } else {
      ElMessage.error(res.msg)
    }
  })
  .catch((error) => {
    if (error == 'cancel') {
      ElMessage.info(error)
    }
  })
}
// 岗位导出
const handleExport = () => {
  proxy.$download('system/role/export', { ...queryParams.value }, `岗位_${ new Date().getTime() }.xlsx`)
}
// 数据权限
// const handleDateScope = (row: { [key: string]: any }) => {
//   const roleId = row.roleId || ids
//   setFormRef.value.openDataScope = true
//   setFormRef.value.title = '分配数据权限'
//   setFormRef.value.getRoleDeptTreeselect(roleId)
//   setFormRef.value.getList(roleId)
// }
// 主体配置
const mainConfig = computed(() => {
  const queryField = 'system.employeeManage.postManagement.queryField.'
  const btns = 'system.employeeManage.postManagement.btns.'
  const columns = 'system.employeeManage.postManagement.columns.'
  const publicKey = 'public.'
  return {
    query: {
      fields: [
        {
          label: t(`${ queryField }roleName`),
          prop: 'roleName',
        },
        {
          label: t(`${ queryField }roleKey`),
          prop: 'roleKey',
        },
        {
          label: t(`${ queryField }status`),
          prop: 'status',
          type: 'select',
          option: {
            placeholder: '请输入岗位状态',
            dictInfo: {
              dict: DictDirection.是否禁用字典,
            },
          },
        },
        {
          label: t(`${ queryField }dateRange`),
          type: 'datePicker',
          prop: 'dateRange',
          option: {
            type: 'daterange',
            placeholder: '开始时间-结束时间',
          },
        },
      ],
      queryParams: queryParams.value,
    },
    btns: [
      {
        title: t(`${ btns }add`),
        icon: Plus,
        directive: [['hasPermi', ['system:role:add']]],
        onClick: handleAdd,
      },
      // {
      //   title: t(`${ btns }edit`),
      //   icon: Edit,
      //   type: 'success',
      //   disabled: multiple.value,
      //   directive: [['hasPermi', ['system:role:edit']]],
      //   onClick: handleUpdate,
      // },
      {
        title: t(`${ btns }del`),
        icon: Delete,
        type: 'danger',
        disabled: multiple.value,
        directive: [['hasPermi', ['system:role:remove']]],
        onClick: handleDelete,
      },
      {
        title: t(`${ btns }export`),
        icon: Download,
        type: 'warning',
        directive: [['hasPermi', ['system:role:export']]],
        onClick: handleExport,
      },
    ],
    table: {
      columns: [
        { type: 'selection', width: '55', align: 'center' },
        {
          label: t(`${ columns }roleId`),
          prop: 'roleId',
          align: 'center',
          width: '90',
        },
        {
          label: t(`${ columns }roleName`),
          prop: 'roleName',
          align: 'center',
        },
        {
          label: t(`${ columns }roleKey`),
          prop: 'roleKey',
          align: 'center',
        },
        {
          label: t(`${ columns }roleSort`),
          prop: 'roleSort',
          align: 'center',
        },
        {
          label: t(`${ columns }status`),
          prop: 'status',
          align: 'center',
          autoFormatter: {
            dict: DictDirection.是否禁用字典,
            rowKey: 'status',
          },
        },
        {
          label: t(`${ columns }createTime`),
          prop: 'createTime',
          align: 'center',
        },
        {
          label: t(`${ columns }operation`),
          align: 'center',
          className: 'custormFixedCol',
          showOverflowTooltip: false,
          width: '200',
          render: (h, params) => {
            const buttons = [
              {
                title: t(`${ publicKey }edit`),
                icon: Edit,
                clickFun: handleUpdate,
                directive: [['hasPermi', ['system:role:edit']]],
              },
              // {
              //   title: '数据权限',
              //   icon: Document,
              //   clickFun: handleDateScope,
              //   directive: [['hasPermi', ['system:role:data']]],
              // },
              {
                title: t(`${ publicKey }del`),
                icon: Delete,
                clickFun: handleDelete,
                directive: [['hasPermi', ['system:role:remove']]],
              },
            ]
            return buttons.map((el) => h(
              ElButton,
              {
                text: true,
                type: 'primary',
                icon: el.icon,
                onClick: () => {
                  el.clickFun(params.row)
                },
              },
              {
                default: () => el.title,
              },
            ))
          },
        },
      ],
      event: {
        onSelectionChange: (rows) => {
          handleSelectionChange(rows)
        },
      },
    },
    api: listRole,
    customKey: 'system/employeeManage/role',
  }
})
</script>
